package springbook.user.service;

import java.util.List;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import springbook.user.domain.Level;
import springbook.user.domain.User;

public class UserServiceTx implements UserService {
	private UserService userService;
	
	private PlatformTransactionManager transactionManager;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setTransactionManager(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public void upgradeLevels() throws Exception {
		//PlatformTransactionManager transactionManager = new org.springframework.jdbc.datasource.DataSourceTransactionManager();
		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
		
		try {
			userService.upgradeLevels();
			transactionManager.commit(status);
		}
		catch(Exception e) {
			transactionManager.rollback(status);
			throw e;
		}

	}

	public void add(User user) {
		if(user.getLevel() == null)
			user.setLevel(Level.BASIC);
		
		userService.add(user);
	}

	public User get(String id) {
		return userService.get(id);
	}

	public List<User> getAll() {
		return userService.getAll();
	}

	public void deleteAll() {
		userService.deleteAll();
	}

	public void update(User user) {
		userService.update(user);
	}
}
